<?php
/**
 * Created by PhpStorm.
 * User: geyouwen
 * Date: 16/7/5
 * Time: 下午2:32
 */

namespace Backend\Controller;


use Think\Controller;
use Think\Exception;
use Think\Model;
use Think\Page;

class BaseController extends Controller
{

    public function __construct()
    {
        parent::__construct();
        if(!session('login_admin'))
        {
            $this->redirect('Backend/passport/login');
        }
        //是否开启日志记录
        if(C('operator_log')) $this->insertLog();

        //权限验证 超级管理员不做验证
        if(session('login_admin.role_id') != 1 )
        {
            $this->checkAuth();
        }
        $site = F('site_cache');
        if(!$site)
        {
            D('settings')->updateSiteCache();
            $site = F('site_cache');
        }
        $this->assign('site_conf', $site);
        $this->assign('admin', session('login_admin'));
        $this->assign('action_name', ACTION_NAME);
    }

    // ajax edit 快捷修改数据
    public function ajax_edit()
    {
        $control_name = CONTROLLER_NAME;
        $source= I('source');
        $control_name = $source ? $source : $control_name;
        $field = I('field');
        $pk    = I('id');
        $value = I('val');
        if(method_exists($this,'_before_save'))
        {
            $this->_before_save($pk, $value);
        }
        try{
            $pk_field = D($control_name)->getPk();
            D($control_name)->where(array($pk_field => $pk))->save(array($field => $value ));
        } catch(Exception $e)
        {
            $msg = $e->getMessage();
            $this->ajaxReturn(array('status' => 0, 'msg' => $msg));
        }
        $return = array(
            'status' => 1,
            'msg'    => ''
        );
        $this->ajaxReturn($return);
    }

    //提示并跳转 success
    public function success($message = '', $jumpUrl = '', $waitSecond = 3)
    {
        $this->assign('message', $message);
        $this->assign('jumpUrl', $jumpUrl);
        $this->assign('waitSecond', $waitSecond);
        $this->display('public/success');
        exit;
    }

    //提示并跳转 error
    public function error($message = '', $jumpUrl = '', $waitSecond = 3)
    {
        if(!$jumpUrl) $jumpUrl = $_SERVER['HTTP_REFERER'];
        $this->assign('message', $message);
        $this->assign('jumpUrl', $jumpUrl);
        $this->assign('waitSecond', $waitSecond);
        $this->display('public/error');
        exit;
    }

    //log 访问日志记录
    public function insertLog()
    {
        $data = array(
            'operator_id' => session('login_admin.admin_id'),
            'controller_name' => CONTROLLER_NAME,
            'action_name'     => ACTION_NAME,
            'addons'          => $_SERVER['REQUEST_URI'],
            'addtime'         => time(),
        );
        M('log')->add($data);
    }


    /**
     * 封装分页
     * @param $model D('') M('') 实例化模型
     * @param string $where 条件
     * @param string $order 排序规则
     * @param int $page_size 每页记录数
     * @return array
     */
    public function getpage($model, $where = '', $order = '', $page_size = 20)
    {
        $count      = $model->where($where)->count();// 查询满足要求的总记录数
        $Page       = new Page($count, $page_size);// 实例化分页类 传入总记录数和每页显示的记录数
        $show       = $Page->show();// 分页显示输出
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = $model->where($where)->order($order)->limit(($Page->firstRow * $Page->listRows).','.$Page->listRows)->select();
        return array(
            'list' => $list,
            'page' => trim($show),
        );
    }

    //登录用户的权限认证
    protected function checkAuth()
    {
        // illegal_operation
        $where = array(
            'module_name' => strtolower(CONTROLLER_NAME),
            'action_name' => strtolower(ACTION_NAME),
            'display'     => 1,
        );
        //获取当前操作的合法信息
        $menu_id = D('menu')->where($where)->getField('id');

        //不合法
        if(!$menu_id)
        {
            if(IS_AJAX){
                $return = array('status' => 0, 'msg' => L('illegal_operation'));
                $this->ajaxReturn($return);
            } else {
                $url = $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : U('backend/index/index');
                $this->error(L('illegal_operation'), $url);
            }
        }

        //合法
        if(!session('login_admin.role_id'))
        {
            if(IS_AJAX){
                $return = array('status' => 0, 'msg' => L('illegal_operation'));
                $this->ajaxReturn($return);
            } else {
                $this->error(L('illegal_operation'), U('backend/passport/login'));
            }
        }
        $menu_ids = D('admin_role')->allauth(session('login_admin.role_id'));
        if(!in_array($menu_id, $menu_ids))
        {
            if(IS_AJAX){
                $return = array('status' => 0, 'msg' => L('error_auth'));
                $this->ajaxReturn($return);
            } else {
                $url = $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : U('backend/index/index');
                $this->error(L('error_auth'), $url);
            }
        }
    }
}